package com.biz.dataSource;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author: create by wucl
 * @version: v1.0
 * @description: com.lfrzzl.java.dataSource
 * @date:2018/9/5
 */
@Aspect
@Component("dataSourceAop")
public class HandlerDataSourceAop {

    private static Logger logger = LoggerFactory.getLogger(HandlerDataSourceAop.class);
    /**
     * @within匹配类上的注解
     * @annotation匹配方法上的注解
     */
    //@Pointcut("@within(com.lfrzzl.java.dataSource.DataSource)||@annotation(com.lfrzzl.java.dataSource.DataSource)")
    //controller层切点  
    @Pointcut("execution(* com.biz.controller.*.*(..))")
    public void pointcut(){}

    @Before(value="pointcut()")
    public void beforeOpt(){
        //先查找方法上的注解，没有的话再去查找类上的注解
        /*MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        DataSource annotation = method.getAnnotation(DataSource.class);
        if(annotation==null){
            annotation = joinPoint.getTarget().getClass().getAnnotation(DataSource.class);
            if(annotation==null){
                return ;
            }
        }
        String dataSourceName = annotation.value();*/
        String dataSourceName = "Master";
        DynamicDataSource.setDataSource(dataSourceName);
        logger.info("切到"+dataSourceName+"数据库");
    }
    @After(value="pointcut()")
    public void afterOpt(){
        DynamicDataSource.clearDataSource();
        logger.info("切回默认数据库");
    }
}
